<template>
	<view class="">
		
		<view class="group-item" @click="handleClick(group)" v-for="(group, index) in groups" :key="group.groupId" @longpress="pressItem(group)">
			<!-- 群组头像 -->

			<view class="group-avatar">
				<image :src="groupAvatarUrl(group)" mode="aspectFill" class="avatar-img"></image>
			</view>

			<!-- 右侧信息区 -->
			<view class="group-info">
				<!-- 群组名称 -->
				<view class="group-name">{{ group.groupName || '未命名群组' }}</view>

				<!-- 成员头像列表 -->
				<view class="member-avatars">
					<view class="member-avatar" v-for="(item, index) in avatarList[group.groupId]" :key="index">
		
						<AvatarFallback v-if="!item.pic" :size="30" :name="item.userName || '未知用户'" class="fallback-avatar"></AvatarFallback>
						<!-- 当 item.pic 有值时，渲染图片 -->
						<image v-else :src="item.pic" mode="aspectFill" class="avatar-img"></image>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import preloadManager from '@/utils/PreloadManager.js';
const linli = uniCloud.importObject('linliChat', { customUI: true });
import AvatarFallback from './AvatarFallback.vue';
import getFriendUserInfo from '../utils/getFriendUserInfo';

export default {
	name: 'group-item',
	components: {
		AvatarFallback
	},
	props: {
		groups: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			avatarList: new Map() // 存储群成员头像信息
		};
	},

	mounted() {
		this.initMembers();
	},
	methods: {
		pressItem(item){
			this.$emit('pressItem',{type:"group",data:item})
		},
		/**
		 * 加载群成员头像
		 */
		groupAvatarUrl(group) {
			if (group.groupPicPath && group.groupPicPath.length > 0) {
				return group.groupPicPath[0].tempFileURL;
			}
			return '/static/default-group-avatar.png';
		},
	async	initMembers() {
			for (group of this.groups) {
			await	this.loadMemberAvatars(group);
			}
		},

		async loadMemberAvatars(group) {
			try {
				const { groupUser = [], groupId } = group;
				if (!groupUser.length) {
					console.log('[Group-Item] 该群组无成员');
					return;
				}

				const maxCount = 9;
				const userIdsToFetch = groupUser.slice(0, maxCount).map((item) => item.userId);
				const userId = this.$store.state.msg.user.userId;
				console.log('[Group-Item] 开始获取成员信息...');
				const userInfoPromises = userIdsToFetch.map((targetId) => getFriendUserInfo(targetId, userId));
				const userInfos = await Promise.all(userInfoPromises);
				console.warn('用户', userInfos);

				// 关键修改：处理每个用户的头像
				const avatarList = await Promise.all(
					userInfos.map(async (userInfo) => {
						let pic = null; // 初始化为 null

						// 如果用户有头像URL，则使用预加载管理器加载
						if (userInfo.nicPic) {
							try {
								pic = await preloadManager.preloadFile(userInfo.nicPic, 'image');
							} catch (error) {
								console.error('[Group-Item] 预加载头像失败:', error);
								// 即使预加载失败，也保持 pic 为 null，让 AvatarFallback 显示
							}
						}
						// 如果用户没有头像，则 pic 保持为 null

						return {
							pic: pic, // 可能是一个URL，也可能是 null
							userName: userInfo.nicName || userInfo.userId || '未知用户'
						};
					})
				);
				this.avatarList.set(groupId, avatarList);
			} catch (error) {
				console.error('[Group-Item] 加载成员头像时发生错误:', error);
				// 错误时，也生成包含 null pic 的数据，以显示 AvatarFallback
				this.avatarList = Array.from({ length: 3 }, (_, i) => ({
					pic: null,
					userName: `成员${i + 1}`
				}));
			}
		},

		/**
		 * 点击事件
		 */
		handleClick(group) {
			this.$emit('toGroupChat', group);
		}
	}
};
</script>

<style lang="scss" scoped>
/* ... (样式部分与之前相同，此处省略) ... */
.group-item {
	display: flex;
	align-items: center;
	padding: 16rpx 20rpx;
	border-bottom: 1rpx solid #f5f5f5;
	&:active {
		background-color: #f2f3f5;
	}
}
.group-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 16rpx;
	overflow: hidden;
	margin-right: 20rpx;
	background-color: #f0f0f0;
}
.member-avatars {
	display: flex;
	margin-top: 8rpx;
	.member-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-right: -8rpx;
		background-color: #f0f0f0;
		&:last-child {
			margin-right: 0;
		}
	}
}
.group-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}
.group-name {
	font-size: 30rpx;
	color: #333;
	font-weight: 500;
}
.avatar-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
.fallback-avatar {
	width: 100%;
	height: 100%;
}
</style>
